<?php
/**
 * https://gitee.com/Mao02
 * http://www.dazhetu.cn/
 * jay_fun 410136330@qq.com
 * Date: 2019/4/17
 * Time: 17:10
 */

class Twig_Adapter implements Yaf_View_Interface
{
    protected $tmplPath;

    protected $extraParams;

    protected $vars = [];

    protected $loader;

    protected $twig;

    protected $template;

    public function __construct($tmplPath,$extraParams = [])
    {
        if ($tmplPath) {
            $this->tmplPath = $tmplPath;
        }
        $this->extraParams=$extraParams;
        $this->loader = new \Twig\Loader\FilesystemLoader($this->tmplPath);
        $this->twig = new \Twig\Environment( $this->loader , $this->extraParams);
        $this->twig->addExtension(new Twig_Extensions_Extension_Text());
        /* 增加两个测试 string array */
        $isArray= new \Twig\TwigTest('array', function ($value) {
            return is_array($value);
        });
        $this->twig->addTest($isArray);
        $isString= new \Twig\TwigTest('string', function ($value) {
            return is_string($value);
        });
        $this->twig->addTest($isString);
    }

    public function assign($name, $value = NULL)
    {
        if (is_array($name)) {
            $this->vars = $name;
            return;
        }
        $this->vars[$name] = $value;
    }

    public function display($tpl, $tpl_vars = NULL)
    {
        echo $this->render($tpl, $tpl_vars);
    }

    public function render($tpl, $tpl_vars = NULL)
    {
        if (!is_null($tpl_vars) && is_array($tpl_vars)) {
            $this->vars = array_merge($this->vars, $tpl_vars);
        }
        $this->template = $this->twig->load($tpl);
        return $this->template->render($this->vars);
    }

    public function setScriptPath($template_dir)
    {
        if ($template_dir) {
            $this->tmplPath = $template_dir;
        }
    }

    public function getScriptPath()
    {
        return $this->tmplPath;
    }
}